// ***********************************************************************
// Assembly         : MVC4Portal
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="ContactManagerController.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using InnovaApp.Portals.MVC4Portal.Models.ViewModels.LayoutViewModels.CustomControllerViewModels;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using System.Web.Security;
using InnovaApp.Layers.CommonLayer;
using InnovaApp.Layers.DomainLayer;
using System.Text;
using System.IO;

namespace InnovaApp.Portals.MVC4Portal.Controllers.ViewControllers.LayoutViewControllers.CustomControllers
{
    /// <summary>
    /// Class ContactManagerController
    /// </summary>
    public class ContactManagerController : _LayoutViewControllers_Base<ContactManager_ViewModel>
    {
        /// <summary>
        /// Initializes data that might not be available when the constructor is called.
        /// </summary>
        /// <param name="requestContext">The HTTP context and route data.</param>
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.eMethodBase = "InnovaApp.Portals.MVC4Portal.Controllers.ViewControllers.LayoutViewControllers.CustomControllers.ContactManagerController";
            base.specificCssCollection = new string[] { "Views/ContactManager.css", string.Format(@"ClientComponents/KendoUI/kendo.{0}.min.css", PortalEnvironment.KendoUITheme.ToLower()) };
            base.specificJSCollection = null;
            base.dynamicJSCollection = new string[] { "/ScriptsG/ContactManagerDynamic.js" };
            base.specificJqueryJSCollection = new string[] { "Views/ContactManager.js" };
            base.externalJs = new string[] { "http://maps.google.com/maps/api/js?sensor=false" };
            base.externalCss = null;
            base.Initialize(requestContext);
        }
        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult Index()
        {
            //Warning, folowing line must be removed if URLFriendlyMode used.
            string eMethod = eMethodBase + ".Index[GET]";
            string language = base.URLReferLanguage;

            base.LocalizeDynamicScript(language, (CurrentContact != null ? CurrentContact.FavoriteLanguage.Language : null));

            //ViewBag.Message = "Modify this template to kick-start your ASP.NET MVC application.";
            using (DataRepositories _dataContext = new DataRepositories())
            {

                base.InitView(
                    pageTitle: Resources.View_ContactManager_PageTitle,
                    openingMessage: string.Empty,
                    specificCssCollection: specificCssCollection,
                    specificJSCollection: specificJSCollection,
                    dynamicJSCollection: dynamicJSCollection,
                    specificJqueryJSCollection: specificJqueryJSCollection,
                    jsVariables: jsVariables,
                    externalJs: externalJs,
                    externalCss: externalCss,
                    metaToAdd: Meta,
                    _dataContext: _dataContext,
                    displayMenus: true,
                    language: language,
                    adminMode: base.AdminMode,
                    currentUser: Membership.GetUser(),
                    usesKendoUI: true,
                    jQueryUITheme: PortalEnvironment.JQueryUITheme,
                    kendoUITheme: PortalEnvironment.KendoUITheme
                    );
                /*
                 * INITIALIZE ContentData with elements from database
                 */
                ContentData._JSVariables.AddRange(BuildMemberLocationArrays(_dataContext));
            }
            ContentData.cap_Tab_GoogleMap = Resources.View_ContactManager_Tabs_capGoogleMapTab;
            ContentData.cap_Tab_List = Resources.View_ContactManager_Tabs_capListTab;
            ContentData._externalJs[0] = string.Format(@"{0}{1}{2}", base.externalJs[0], "&language=", language);
            /*
             * INITIALIZE ContentData with elements not coming from database
             */

            return View(ContentData);
        }

        /// <summary>
        /// Builds the member location array.
        /// </summary>
        /// <param name="_dataContext">The _data context.</param>
        /// <returns>System.String.</returns>
        private List<string> BuildMemberLocationArrays(DataRepositories _dataContext)
        {
            List<string> toReturn = new List<string>();
            StringBuilder oSB1 = new StringBuilder();
            oSB1.Append("var MemberLocations = [");
            List<Contact> dbContacts = _dataContext.Contact_Rep.GetAll().ToList();
            List<string> iconList = new List<string>();
            var count = dbContacts.Count;
            for (var i = 0; i < count; i++)
            {
                var c = dbContacts[i];
                List<string> lstRow = new List<string>();
                //Label
                lstRow.Add(BuildContactLabel(c));
                //Latitude
                if (c.GoogleMapLat.HasValue)
                {
                    lstRow.Add(c.GoogleMapLat.ToString().Replace(",", "."));
                }
                //Longitude
                if (c.GoogleMapLng.HasValue)
                {
                    lstRow.Add(c.GoogleMapLng.ToString().Replace(",", "."));
                }
                //fileName
                string fileName = "''";
                if (!string.IsNullOrEmpty(c.IconPath))
                {
                    fileName = Path.GetFileNameWithoutExtension(c.IconPath);
                    fileName += "_google";
                    fileName += Path.GetExtension(c.IconPath);
                    fileName = c.IconPath.Replace(Path.GetFileName(c.IconPath), fileName);
                    fileName = string.Format("'{0}'", fileName);
                    lstRow.Add(fileName);
                }
                if (lstRow.Count == 4)
                {
                    string row = "[" + string.Join(",", lstRow.ToArray()) + "]";
                    iconList.Add(row);
                }
            }
            if (iconList.Count > 0)
            {
                oSB1.Append(string.Join(",", iconList));
            }
            oSB1.Append("];\n");
            toReturn.Add(oSB1.ToString());
            return toReturn;
        }

        /// <summary>
        /// Builds the contact label.
        /// </summary>
        /// <param name="c">The asynchronous.</param>
        /// <returns>System.String.</returns>
        private string BuildContactLabel(Contact c)
        {
            string toReturn = string.Empty;
            var genre = INNOVACALL.Framework.Common.MVCHelpers.Localization.CommonLocalization.LookupResource(typeof(InnovaApp.Layers.ResourcesLayer.Properties.Resources), c.Genre.Name).Replace("'", "''"); ;
            var firstName = c.FirstName.Trim().Replace("'", "''");
            var lastName = c.LastName.Trim().Replace("'", "''");
            toReturn = genre;
            toReturn += (toReturn.Length == 0 ? "" : " ");
            toReturn += (string.IsNullOrEmpty(firstName) ? string.Empty : firstName);
            toReturn += (toReturn.Length == 0 ? "" : " ");
            toReturn += (string.IsNullOrEmpty(lastName) ? string.Empty : lastName);
            toReturn = "'" + toReturn + "'";
            return toReturn;
        }

    }
}
